import { Component } from '@angular/core';
import { IonicPage, NavController, ViewController, Platform, NavParams } from 'ionic-angular';
import { HttpProvider } from '../../../providers/http/http';
import { StorageProvider } from '../../../providers/storage/storage';
import { DialogProvider } from '../../../providers/dialog/dialog';
import { Md5 } from "ts-md5/dist/md5";
import { BLE } from '@ionic-native/ble';
import { OrderDataService } from '../../../providers/service/order-data.service';
import { BleProvider } from '../../../providers/ble/ble';
import { EventProvider } from '../../../providers/event/event' 

declare let Wechat: any;
/**
 * Generated class for the LoginPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
	selector: 'page-login2',
	templateUrl: 'login2.html',
})
export class Login2Page {
	/*模型设置*/
	public loginInfo = {
		UserName: '',
		PassWord: ''
	};

	public info;

	public notifyInfo = new Array();;

	test;

	public devices = new Array();

	characters;
	constructor(
		public navCtrl: NavController,
		public ble: BLE,
		public viewCtrl: ViewController,
		public http: HttpProvider,
		public storage: StorageProvider,
		public dialog: DialogProvider,
		public b: BleProvider,
		public platform: Platform,
		public params: NavParams,
		public order: OrderDataService,
		public event: EventProvider ) {
		this.characters = this.params.get('characterNum');
	}

	ionViewDidLoad() {
		console.log('ionViewDidLoad Login2Page');
	}

	// 页面跳转的方式
	register() {
		this.navCtrl.push('RegisterPage');
	}

	forgetpwd() {
		this.navCtrl.push('ForgetPwdPage');
	}

	dismiss() {
		console.log(this.characters)
		this.viewCtrl.dismiss({ asdasd: '1112222' });
		return { asdasd: '1112222' };
	}
	/**
	 * 用户登录
	 */
	async loginOnSuccess() {
		if (this.loginInfo.UserName == '' || this.loginInfo.UserName == null) {
			this.dialog.showAlert('请输入手机号码', '');
			return;
		}
		if (this.loginInfo.PassWord == '' || this.loginInfo.PassWord == null) {
			this.dialog.showAlert('请输入密码', '');
			return;
		}
		else if (this.loginInfo.PassWord.length != 6) {
			this.dialog.showAlert('密码只能6位', '');
			return;
		}
		/*把表单的空值传到定义的属性名*/
		var params = {
			username: this.loginInfo.UserName,
			password: this.loginInfo.PassWord
		};
		/*调用接口的方式,这种写法接受参数需要json的格式*/
		const res = await this.http.postJson('', 'users/member/login', { 'phone': params.username, 'password': params.password }, '')
			.then(res => {
				console.log(res)
				if (res['status'] == 200) {
					this.dialog.showAlert('您好' + res['data']['nickname'], res['message']);
					this.storage.saveStorage("login_info", res['data']);
					this.http.setAuthorization(res['data']['access_token']);
					this.navCtrl.push('TabsPage');
				} else {
					this.dialog.showAlert(res['message'], '');
				}
			});
	}

	selected(id) {
		this.info = id;
	}

	scan() {
		this.ble.enable();
		this.devices.splice(0);
		this.ble.startScan([]).subscribe(device => {
			this.devices.push(device);
			this.dialog.showAlert(JSON.stringify(device.name), JSON.stringify(device));
			this.ble.readRSSI(device.id).then(level => {
				this.dialog.showAlert(level, '');
			});
		});
	}

	connect() {
		this.ble.connect(this.info).subscribe(res => {
			this.dialog.showAlert(JSON.stringify(res), '');
		});
	}

	write() {
		var head = {
			bHeadMark: this.stringToHex('LBK'),
			bVer: '01',
			bLength: '20',
			bCmdld: '0200',
			bSeq: '0000',
			bCks: '0A0A'
		}

		// let a = {
		// 	year: new Uint8Array(1),
		// }

		// let dataPag = [
		// 	new ArrayBuffer(20),
		// 	new ArrayBuffer(20),
		// ];

		// var headBuffer = new ArrayBuffer(12);


		// head.bHeadMark = this.hexTo8Bytes('100', 3);
		// head.bVer = this.hexTo8Bytes('10', 1);
		// head.bLength = this.hexTo16Bytes((500).toString(16), 2);
		// head.bCmdld = this.hexTo16Bytes('200', 2);
		// let i = 0;
		// for (var key in head) {
		// 	head[key].forEach(ele => {
		// 		headBuffer[i] = ele;
		// 		i++;
		// 	});
		// }


		let time = {
			year: '18',
			month: '3',
			day: '31',
			hour: '15',
			min: '46',
			sec: '12',
		}

		let num = {
			device_id: '1',
			reserver_code: '1234567',
			index_code: '14'
		}

		let charge = {
			up1: 1000,
			up2: 500,
		}

		let discharge = {
			userid: '12345678',
			mins: '00000001'
		}

		var headBuffer = this.assembleHeadBuffer('LKB', 1, 20, '0200', 0, 11);

		let write = headBuffer + discharge.userid + discharge.mins;

		// let buf = this.stringToHex(write);
		// let list = buf.split(',');
		// var a = new Uint8Array(20);
		// for (let i = 0; i < list.length - 1; i++) {
		// 	a[i] = parseInt(list[i],16);
		// }




		console.log(write)
		this.writebuffer(write);

		// var timeBuffer = this.assembleTimeBuffer(time.year,time.month,time.day,time.hour,time.min,time.sec);
		// this.writebuffer(timeBuffer);

		// var dischargeBuffer = this.assembledisChargeBuffer(discharge.userid,discharge.mins);
		// this.writebuffer(headBuffer);

		let dataPag = [
			new ArrayBuffer(20),
			new ArrayBuffer(20),
		];



	}

	a: any;
	public async addTestData() {
		let a = await this.order.save({ 'message': ('test' + Math.round(Math.random() * 1000)) });
	}

	public async delTestData() {

		let a = await this.order.find((b) => b.key !== '');
		this.dialog.showAlert('提示', a);
		await this.order.delete((c) => c.key === a[0].key);
	}

  /**
   * 蓝牙写入 0110
   * @param buf 
   */
  async write0110() {
    let head = {
      bHeadMark: 'LKB', //3字节 要经过ASCII码转换
      bVer: 1, //1字节
      bLength: 18, //2字节
      bCmdld: '0110', //2字节
      bSeq: 0, //2字节
      bCks: 1111 //2字节
    }

    // let headBuffer = this.assembleHeadBuffer(head.bHeadMark, head.bVer, head.bLength, head.bCmdld, head.bSeq, head.bCks);
    // let year = this.supplementZer0(parseInt(new Date().getFullYear().toString().slice(2, 4)).toString(16), 1) + this.supplementZer0((new Date().getMonth() + 1).toString(16), 1) + this.supplementZer0((new Date().getDate()).toString(16), 1) + this.supplementZer0((new Date().getHours()).toString(16), 1) + this.supplementZer0((new Date().getMinutes().toString(16)), 1) + this.supplementZer0((new Date().getSeconds().toString(16)), 1);
	// headBuffer = headBuffer + year;
	let headBuffer = '4C4B42010012011000000A0A120403131300';
    var a1 = new Uint8Array(18);
    // this.dialog.showAlert('0110提示', headBuffer);
    let j = 0;
    for (let i = 0; i < headBuffer.length - 1; i++) {
      a1[i] = parseInt(headBuffer[j] + headBuffer[j + 1], 16);
      j = j + 2;
    }
    await this.ble.write(this.info, 'FEC0', 'FEC1', a1.buffer);
  }

    /**
   * 蓝牙写入 0120
   * @param buf 
   */
	async write0120(device) {
		let head = {
			bHeadMark: 'LKB', //3字节 要经过ASCII码转换
			bVer: 1, //1字节
			bLength: 12, //2字节
			bCmdld: '0120', //2字节
			bSeq: 0, //2字节
			bCks: 1111 //2字节
		}
		device = '00000001';
		let headBuffer = this.assembleHeadBuffer(head.bHeadMark, head.bVer, head.bLength, head.bCmdld, head.bSeq, head.bCks);
		let datapacket = device + '0000000000000001';

		var a1 = new Uint8Array(12);
		this.dialog.showAlert('提示', headBuffer);
		let j = 0;
		for (let i = 0; i < headBuffer.length - 1; i++) {
			a1[i] = parseInt(headBuffer[j] + headBuffer[j + 1], 16);
			j = j + 2;
		}
		// await this.notify()
		await this.ble.write(this.info, 'FEC0', 'FEC1', a1.buffer);

		var a2 = new Uint8Array(12);
		this.dialog.showAlert('提示', headBuffer);
		let j2 = 0;
		for (let i2 = 0; i2 < headBuffer.length - 1; i2++) {
			a1[i2] = parseInt(headBuffer[j2] + headBuffer[j2 + 1], 16);
			j2 = j2 + 2;
		}
		await this.ble.write(this.info, 'FEC0', 'FEC1', a2.buffer);
	}

	/**
 * 蓝牙写入 0300
 * @param buf 
 */
	async write0030() {
		let head = {
			bHeadMark: 'LKB', //3字节 要经过ASCII码转换
			bVer: 1, //1字节
			bLength: 12, //2字节
			bCmdld: '0300', //2字节
			bSeq: 0, //2字节
			bCks: 1111 //2字节
		}

		let headBuffer = this.assembleHeadBuffer(head.bHeadMark, head.bVer, head.bLength, head.bCmdld, head.bSeq, head.bCks);
		var a1 = new Uint8Array(12);
		this.dialog.showAlert('提示', headBuffer);
		let j = 0;
		for (let i = 0; i < headBuffer.length - 1; i++) {
			a1[i] = parseInt(headBuffer[j] + headBuffer[j + 1], 16);
			j = j + 2;
		}
		// await this.notify()
		await this.ble.write(this.info, 'FEC0', 'FEC1', a1.buffer);
	}

  /**
   * 蓝牙写入 0020
   * @param buf 
   */
  async write0020(headBuffer: String, dataBuffer: String) {
	// this.dialog.showAlert('0020提示', buf);
	headBuffer = '4C4B4201001802000000';
	dataBuffer = '1205190A1E09000000120003';
	headBuffer = headBuffer + await this.checksum(headBuffer, 10);
    // let year = this.supplementZer0(parseInt(new Date().getFullYear().toString().slice(2, 4)).toString(16), 1) + this.supplementZer0((new Date().getMonth() + 1).toString(16), 1) + this.supplementZer0((new Date().getDate()).toString(16), 1) + this.supplementZer0((new Date().getHours()).toString(16), 1) + this.supplementZer0((new Date().getMinutes().toString(16)), 1) + this.supplementZer0((new Date().getSeconds().toString(16)), 1);
    // dataBuffer = year + dataBuffer;
    await this.write0020split(headBuffer,12);
    await this.write0020split(dataBuffer,12);
  }

  async write0020split(buf: String, num: number) {
    var a1 = new Uint8Array(num);
    this.dialog.showAlert('0020提示', buf);
    let j = 0;
    for (let i = 0; i < buf.length - 1; i++) {
      a1[i] = parseInt(buf[j] + buf[j + 1], 16);
      j = j + 2;
    }
    // await this.notify()
    await this.ble.write(this.info, 'FEC0', 'FEC1', a1.buffer);
  }


	writebuffer(buf: String) {
		var a = new Uint8Array(20);

		a[0] = 0x4c;
		a[1] = 0x4B;
		a[2] = 0x42;
		a[3] = 0x01;
		a[4] = 0x00;
		a[5] = 0x14;
		a[6] = 0x02;
		a[7] = 0x00;
		a[8] = 0x00;
		a[9] = 0x00;
		a[10] = 0x0A;
		a[11] = 0x0A;
		a[12] = 0x12;
		a[13] = 0x34;
		a[14] = 0x56;
		a[15] = 0x78;
		a[16] = 0x00;
		a[17] = 0x00;
		a[18] = 0x00;
		a[19] = 0x01;

		console.log(a);
		// let list = buf.split(',');

		var a1 = new Uint8Array(20);
		// a1[0] = parseInt(buf[0]+buf[1],16);
		// a1[1] = parseInt(buf[2]+buf[3],16);
		// a1[2] = parseInt(buf[4]+buf[5],16);
		let j = 0;
		for (let i = 0; i < buf.length - 1; i++) {
			a1[i] = parseInt(buf[j] + buf[j + 1], 16);
			j = j + 2;
		}


		console.log(a1);

		this.ble.write(this.info, 'FEC0', 'FEC7', a1.buffer).then(buffer => {
			this.test = buffer
			this.dialog.showAlert('提示', String.fromCharCode.apply(null, new Uint8Array(buffer)));
		});
	}

	read() {
		// 设备
		this.ble.read(this.info, 'FEC0', 'FEC2').then(buffer => {
			this.dialog.showAlert('提示', String.fromCharCode.apply(null, new Uint8Array(buffer)));
		});
	}

	notify() {
		this.dialog.showAlert('监听提示1', 'adfad');
		let a = '';
		this.ble.startNotification(this.info, 'FEC0', 'FEC2').subscribe(buffer => {
			a = '';
			var adData = (new Uint8Array(buffer)).toString().split(',');
			for (let b of adData) {
				a = a + this.supplementZer0(parseInt(b).toString(16), 1);
			}

			this.dialog.showAlert('监听提示1', a);
		});

		// this.ble.startNotification(this.info, 'FEC0', 'FEC2').subscribe(buffer => {
		//   this.dialog.showAlert('监听提示', String.fromCharCode.apply(null, new Uint8Array(buffer)));
		//   a = String.fromCharCode.apply(null, new Uint8Array(buffer));
		// });
	}

	stopnotify() {
		this.ble.stopNotification(this.info, 'FEC0', 'FFd1').then(buffer => {
			this.dialog.showAlert('提示', String.fromCharCode.apply(null, new Uint8Array(buffer)));
		});
	}

	disconect() {
		this.ble.disconnect(this.info);
	}

	state() {
		this.ble.startStateNotifications().subscribe(state => {
			if (state == 'off') {
				this.dialog.showAlert('蓝牙已关闭', '');
			}
		});
	}

	stopstate() {
		this.ble.stopStateNotifications().then(state => {

		});
	}



	/**
	 * 生成头包
	 * @param bHeadMark 
	 * @param bVer 
	 * @param bLength 
	 * @param bCmdld 
	 * @param bSeq 
	 * @param bCks 
	 */
	assembleHeadBuffer(bHeadMark: String, bVer: number, bLength: number, bCmdld: String, bSeq: number, bCks: number) {
		let head = {
			bHeadMark: null,
			bVer: null,
			bLength: null,
			bCmdld: null,
			bSeq: null,
			bCks: null
		}

		let headBuffer: String;

		head.bHeadMark = this.stringToHex(bHeadMark);
		head.bVer = this.supplementZer0((bVer).toString(16), 1);
		head.bLength = this.supplementZer0((bLength).toString(16), 2);
		head.bCmdld = bCmdld;
		head.bSeq = this.supplementZer0((bSeq).toString(16), 2);
		head.bCks = this.supplementZer0((bCks).toString(16), 2);

		headBuffer = head.bHeadMark + head.bVer + head.bLength + head.bCmdld + head.bSeq + head.bCks;

		return headBuffer;

	}

	/**
	 * 用0补充位数
	 * @param str 
	 * @param num 
	 */
	supplementZer0(str: String, num: number): any {
		var pos = 0;
		num *= 2;
		var len = str.length;

		if (len !== num) {
			for (let i = 0; i < num - len; i++) {
				str = '0' + str;
			}
		}


		return str;
	}

	// let rc_index = 01;   
	// let chargingtimerequest = 0001; 
	//   let chargingtime = 0001; 
	//    let userid = 00000012;      
	//   let deviceid = 01020304;    
	//   let datetime = 000101000033; 
	//  let Reserved;//0xFF




	/**
	 * 字符串转Byte 8
	 * @param str 字符串
	 * @param num 使用的字节数
	 */
	hexTo8Bytes(str: String, num: number) {
		var pos = 0;
		num *= 2;
		var len = str.length;

		if (len !== num) {
			for (i = 0; i < num - len; i++) {
				str = '0' + str;
			}
			len = str.length;
		}

		len /= 2;

		var hexA = new Uint8Array(len);

		for (var i = 0; i < len; i++) {

			var s = str.substr(pos, 2);

			var v = parseInt(s, 16);

			hexA[i] = v;

			pos += 2;

		}

		return hexA;
	}



	/**
	 * 字符串转Byte 16
	 * @param str 字符串
	 * @param num 使用的字节数
	 */
	hexTo16Bytes(str: String, num: number) {
		var pos = 0;
		num *= 2;
		var len = str.length;

		if (len !== num) {
			for (i = 0; i < num - len; i++) {
				str = '0' + str;
			}
			len = str.length;
		}

		len /= 2;

		var hexA = new Uint16Array(len);

		for (var i = 0; i < len; i++) {

			var s = str.substr(pos, 2);

			var v = parseInt(s, 16);

			hexA[i] = v;

			pos += 2;

		}

		return hexA;
	}

	stringToHex(str) {
		var val = "";
		for (var i = 0; i < str.length; i++) {
			if (val == "")
				val = str.charCodeAt(i).toString(16);
			else
				val += str.charCodeAt(i).toString(16);
		}
		return val;
	}

	authenticateusingWechat() {
		var scope = "snsapi_userinfo",
			state = "_" + (+new Date());
		Wechat.auth(scope, state, (response) => {
			// you may use response.code to get the access token.
			this.dialog.showAlert('微信验证成功？', JSON.stringify(response));
		}, (reason) => {
			this.dialog.showAlert('微信验证失败？', JSON.stringify(reason));
		});
	}

	sharetext() {
		Wechat.share({
			text: "This is just a plain string",
			scene: Wechat.Scene.TIMELINE   // share to Timeline
		}, () => {
			this.dialog.showAlert('微信分享成功？', '');
		}, (reason) => {
			this.dialog.showAlert('微信风险失败？', JSON.stringify(reason));
		});
	}


	checksum(data, size) {

		let buffer = new Uint8Array(18);
		let j = 0;
		for (let i = 0; i < data.length - 1; i++) {
			buffer[i] = (parseInt(data[j] + data[j + 1], 16) & 0xff);
			j = j + 2;
		}
		let Cksum = 0;
		let num = 0;
		while (size > 1) {
			Cksum = ((Cksum + buffer[num]) & 0xffffffff);
			size = ((size - 1) & 0xffff);
			num++;
		}
		if (size) {
			Cksum = ((Cksum + buffer[17]) & 0xffffffff);
		}

		while (((Cksum >> 16) & 0xffff)) {
			Cksum = ((Cksum >> 16) & 0xffff) + (Cksum & 0xffff);
		}

		return (65535 - Cksum).toString(16);
	}

	/**
	 * 蓝牙写入 APP校验
	 * @param buf 
	 */
	async writeAPP(userid) {



		this.ble.startNotification(this.info, 'FFF0', 'FFF2').subscribe(buffer => {
			let a = '';
			a = '';
			var adData = (new Uint8Array(buffer)).toString().split(',');
			for (let b of adData) {
				a = a + this.supplementZer0(parseInt(b).toString(16), 1);
			}

			this.dialog.showAlert('监听提示1', String.fromCharCode.apply(null, new Uint8Array(buffer)));
		});


		let head = {
			identify: 'KEY:', //3字节 要经过ASCII码转换
			userid: 12, //1字节
			timestamp: new Date().getTime(), //2字节
			randnum: parseInt((Math.random() * (9999 - 0 + 1) + 0).toString(), 10), //2字节
			checknum: 1111 //2字节
		}

		let buffer = {
			identify: null,
			userid: null,
			timestamp: null,
			randnum: null,
			checknum: null,
		}

		buffer.identify = this.stringToHex(head.identify);
		buffer.userid = this.supplementZer0((head.userid).toString(), 4);
		buffer.timestamp = this.supplementZer0((head.timestamp).toString(16), 8);
		buffer.randnum = this.supplementZer0((head.randnum).toString(16), 2);
		let str = buffer.identify + buffer.userid + buffer.timestamp + buffer.randnum;
		buffer.checknum = this.checksum(str, 18);

		let headBuffer = buffer.identify + buffer.userid + buffer.timestamp + buffer.randnum + buffer.checknum;
		// let headBuffer = '4b45593affffffff000001635c68740a8d4af863'
		var a1 = new Uint8Array(20);
		this.dialog.showAlert('校验提示', headBuffer);
		let j = 0;
		for (let i = 0; i < headBuffer.length - 1; i++) {
			a1[i] = parseInt(headBuffer[j] + headBuffer[j + 1], 16);
			j = j + 2;
		}
		await this.ble.write(this.info, 'FFF0', 'FFF1', a1.buffer);
	}


}
